<?php

namespace app\common\model\haipi;


use think\facade\Db;
use think\Model;

/**
 * OpenArea
 */
class OpenArea extends Model
{
    // 表名
    protected $name = 'haipi_open_area';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

 
    
    public function getAreasAttr($value, $data): array
    {
        
       $areas = [$data['province_code'],$data['city_code']];
    
        $value = Db::name('area')->whereIn('code',$areas)->column('id');
      
        if ($value === '' || $value === null) return [];
        if (!is_array($value)) {
            return explode(',', $value);
        }
        return $value;
    }

 
    public function setAreasAttr($value)
    {
      
        $value = is_array($value) ? $value : explode(',',$value) ;
        
        $province = Db::name('area')->whereIn('id',$value[0])->value('code');
        $this->set('province_code', $province);

        $city  = Db::name('area')->whereIn('id',$value[1])->value('code');
        $this->set('city_code',  $city );
    }
 
    public function getAreasTextAttr($value, $row): string
    {
    
        $row['areas'] = [$row['province_code'], $row['city_code']] ??'';

        if ($row['areas'] === '' || $row['areas'] === null) return '';
        $cityNames = Db::name('area')->whereIn('code', $row['areas'])->column('name');
        return $cityNames ? implode(',', $cityNames) : '';
    }

    public function getCityAttr($value, $row): string{
        return  Db::name('area')->whereIn('code', $row['city_code'])->value('name');
    }
}